package test.top1.com.atguigu.app.dim_dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.apache.kafka.clients.producer.ProducerRecord;
import test.top1.com.atguigu.app.fun.DIMSinkFunction;
import test.top1.com.atguigu.app.fun.DimDwdTableProcessFunction;
import test.top1.com.atguigu.app.fun.DwdTableProcessFunction;
import test.top1.com.atguigu.bean.TableProcess;
import test.top1.com.atguigu.utils.MyKafkaUtil;

import javax.annotation.Nullable;

/**
 * ClassName: Dwd08_BaseDBApp
 * Package: test.top1.com.atguigu.app.dwd.db
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/5/4 18:29
 * @Version 1.0
 */

//数据流:web/app -> Mysql -> Maxwell -> Kafka(ODS) -> FlinkApp -> Phoenix(DIM)
//数据流:web/app -> MySQL -> Maxwell -> Kafka(ODS) -> FlinkApp -> Kafka(DWD)
//程 序:Mock -> Mysql -> Maxwell -> Kafka(ZK) -> BaseDBApp(FlinkCDC) -> Phoenix(HBase ZK/HDFS)
//程 序:mock -> Mysql -> Maxwell -> Kafka(ZK) -> BaseDBApp(FlinkCDC) -> Kafka(ZK)
public class BaseDBApp {
    public static void main(String[] args) throws Exception {

        //TODO 1.创建运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 配置环境信息生产环境得有

//         env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //TODO 2.从kafka读取 topic_db 数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("topic_db", "dwd08_base_db_app_1109"),
                WatermarkStrategy.noWatermarks(), "kafka-source");

        //TODO 3.判断是否为json数据
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    try {
                        JSONObject jsonObject = JSON.parseObject(value);
                        out.collect(jsonObject);
                    } catch (JSONException e) {
                        System.out.println("脏数据：" + value);
                    }
                }
            }
        });

        //TODO 4.使用flinkCDC从mysql读取配置信息
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
                .hostname("hadoop102")
                .port(3306)
                .username("root")
                .password("000000")
                .databaseList("gmall_config")
                .tableList("gmall_config.table_process")
                .deserializer(new JsonDebeziumDeserializationSchema())
                .startupOptions(StartupOptions.latest())
                .build();
        DataStreamSource<String> mysqlDS = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql-source");

        //TODO 5.将配置信息转化为广播流
        MapStateDescriptor<String, TableProcess> mapStateDescriptor = new MapStateDescriptor<>("map-state", String.class, TableProcess.class);

        BroadcastStream<String> broadcastStream = mysqlDS.broadcast(mapStateDescriptor);

        //TODO 6.连接主流和广播流
        BroadcastConnectedStream<JSONObject, String> connectedStream = jsonObjDS.connect(broadcastStream);

        //TODO 7.处理主流数据
        OutputTag<JSONObject> outputTag = new OutputTag<JSONObject>("hbase") {
        };
        SingleOutputStreamOperator<JSONObject> processDS =
                connectedStream.process(new DimDwdTableProcessFunction(mapStateDescriptor,outputTag));

        //TODO 8.将主流数据写出到kafka，同时提取侧输出流
        processDS.addSink(MyKafkaUtil.getFlinkKafkaProducer(new KafkaSerializationSchema<JSONObject>() {
            @Override
            public ProducerRecord<byte[], byte[]> serialize(JSONObject jsonObject, @Nullable Long aLong) {
                return new ProducerRecord<>(jsonObject.getString("sink_table"),jsonObject.getString("data").getBytes());
            }
        }));
        DataStream<JSONObject> hbaseDS = processDS.getSideOutput(outputTag);
        hbaseDS.print("hbase-->");
        hbaseDS.addSink(new DIMSinkFunction());

        //TODO 9.执行任务
        env.execute();
    }
}
